﻿using Bricks.Business.Service;
using Bricks.Component.Utils.Const;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Bricks.Component.Utils.Extensions;
using Bricks.Site.Models;
using System.Text;
using Bricks.Business.Service.CommonSupport;
using Bricks.Component.Utils;
using Bricks.Site.Web.CommonUtils;
using System.Xml;
using Bricks.Business.Models.ScheduleManagement;

namespace Bricks.Site.Web.Controllers
{
    [Export]
    public class MonthPlanController : BaseController
    {
        #region 属性
        [Import]
        public IFlowNodeService FlowNodeService { get; set; }
        [Import]
        public IBaklogTaskService BaklogTaskService { get; set; }
        [Import]
        public IFlowUtilsService FlowUtilsService { get; set; }
        [Import]
        public IMonthPlanService MonthPlanService { get; set; }
        #endregion

        #region 主界面加载
        public ActionResult MonthPlanList()
        {
            ContractFilterView contractFilterView = new ContractFilterView();
            contractFilterView.UserType = "1";
            ViewBag.ToolBarInfo = CommonUtils.ScheduleManagementUtils.ConstructToolsAndSetView(contractFilterView, User.Identity.Name, base.GetUserMenuActions(), "MonthPlanList");
            return View(contractFilterView);
        }

        public ActionResult GetMonthPlanList(string projectID, string contractType, string contractID)
        {
            Guid guidProjectID = string.IsNullOrEmpty(projectID) ? GuidHelper.NewGuid() : projectID.ToGuid();
            Guid guidContractID = string.IsNullOrEmpty(contractID) ? GuidHelper.NewGuid() : contractID.ToGuid();
            return Json(MonthPlanService.GetMonthPlanList(guidProjectID, contractType, guidContractID), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetMonthPlanDetailList(string projectID, string contractType, string contractID, string year, string month, string monthPlanID)
        {
            Guid guidProjectID = projectID.ToGuid();
            Guid guidContractID = contractID.ToGuid();
            Guid guidMonthPlanID = monthPlanID.ToGuid();
            return Json(MonthPlanService.GetMonthPlanDetailList(guidProjectID, contractType, guidContractID, year, month, guidMonthPlanID), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetMonthPlanListForPreview(string projectID, string contractType, string contractIDStr)
        {
            Guid guidProjectID = string.IsNullOrEmpty(projectID) ? GuidHelper.NewGuid() : projectID.ToGuid();
            List<Guid> lstContractID = new List<Guid>();
            string[] contractIDArr = contractIDStr.Split(',');
            foreach (string contractID in contractIDArr)
            {
                lstContractID.Add(contractID.ToGuid());
            }
            return Json(MonthPlanService.GetMonthPlanListForPreview(guidProjectID, contractType, lstContractID), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetMonthPlanDetailListForPreview(string projectID, string contractType, string contractIDStr, string year, string month)
        {
            Guid guidProjectID = string.IsNullOrEmpty(projectID) ? GuidHelper.NewGuid() : projectID.ToGuid();
            List<Guid> lstContractID = new List<Guid>();
            string[] contractIDArr = contractIDStr.Split(',');
            foreach (string contractID in contractIDArr)
            {
                lstContractID.Add(contractID.ToGuid());
            }
            return Json(MonthPlanService.GetMonthPlanDetailListForPreview(guidProjectID, contractType, lstContractID, year, month), JsonRequestBehavior.AllowGet);
        }
        #endregion

        public ActionResult Delete(string monthPlanID)
        {
            Guid guidMonthPlanID = monthPlanID.ToGuid();
            var result = MonthPlanService.Delete(guidMonthPlanID);
            if (result.ResultType == OperationResultType.Success)
                return Content(OperationResultType.Success.ToString());
            return Content(result.Message);
        }

        #region 单据界面加载
        public ActionResult MonthPlan(string sourceType, string processType, string sourceID, string associatedNodeCode, string lastUpdateUserDepartment, string lastUpdateUser, string monthPlanID, string projectID, string contractType, string contractID)
        {
            MonthPlanView monthPlanView = null;
            string processdOrCirculatedNodeCode = string.Empty;
            string processdOrCirculatedUserDepartment = string.Empty;
            if (sourceType == "1") //新增总量维护
            {
                string flowCode = "MonthPlan";
                string nodeCode = FlowNodeService.GetFlowNodeByNodeCode(flowCode, true, "").NodeCode;
                monthPlanView = new MonthPlanView();
                monthPlanView.ID = Guid.NewGuid();
                monthPlanView.FlowCode = flowCode;
                monthPlanView.ProjectID = projectID.ToGuid();
                monthPlanView.ContractType = contractType;
                monthPlanView.ContractID = contractID.ToGuid();
                monthPlanView.Year = "2012";
                monthPlanView.Month = "1";
                monthPlanView.Unit = "万元";
                monthPlanView.RequestPerson = User.Identity.Name;
                monthPlanView.RequestDate = DateTime.Now;
                monthPlanView.HandleState = "0";
                monthPlanView.AssociatedNodeCode = nodeCode;
                monthPlanView.LastUpdateUserDepartment = lastUpdateUserDepartment;
                monthPlanView.LastUpdateUser = User.Identity.Name;
                processdOrCirculatedNodeCode = monthPlanView.AssociatedNodeCode;
                processdOrCirculatedUserDepartment = lastUpdateUserDepartment;
            }
            else
            {
                monthPlanView = MonthPlanService.GetMonthPlanByID(monthPlanID.ToGuid());
            }

            if (sourceType == "2" && processType == "1")
            {
                monthPlanView.AssociatedNodeCode = associatedNodeCode;
                monthPlanView.LastUpdateUserDepartment = lastUpdateUserDepartment;
                monthPlanView.LastUpdateUser = lastUpdateUser;
            }

            if (sourceType == "2" || (sourceType == "3" && (processType == "1" || processType == "4" || processType == "5")))
            {
                processdOrCirculatedNodeCode = associatedNodeCode;
                processdOrCirculatedUserDepartment = lastUpdateUserDepartment;
            }
            monthPlanView.MonthPlanDetailListJson = "";
            monthPlanView.SourceType = sourceType;
            monthPlanView.ProcessType = processType;
            monthPlanView.SourceID = sourceID;
            monthPlanView.ProcessdOrCirculatedNodeCode = processdOrCirculatedNodeCode;
            monthPlanView.ProcessdOrCirculatedUserDepartment = processdOrCirculatedUserDepartment;
            ConstructTools(monthPlanView);
            return View(monthPlanView);
        }

        public ActionResult GetMonthPlanDetailListForFlow(string projectID, string contractType, string contractID, string year, string month, string monthPlanID)
        {
            Guid guidProjectID = projectID.ToGuid();
            Guid guidContractID = contractID.ToGuid();
            Guid guidMonthPlanID = monthPlanID.ToGuid();
            return Json(MonthPlanService.GetMonthPlanDetailListForFlow(guidProjectID, contractType, guidContractID, year, month, guidMonthPlanID), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 根据功能权限和业务权限构造工具栏菜单按钮
        private void ConstructTools(MonthPlanView monthPlanView)
        {
            List<UIFunctionView> menuActions = base.GetUserMenuActions();
            StringBuilder sb = new StringBuilder();

            //过程管理列表单据双击或单击超链接，只能查看
            if (monthPlanView.SourceType == "0")
            {
                SetAllDisabled(menuActions, sb);
            }
            //过程管理列表新增按钮,初始化只能保存
            else if (monthPlanView.SourceType == "1")
            {
                SetOneButtonEnabled(menuActions, sb, "Save");
            }
            #region 待办列表
            else if (monthPlanView.SourceType == "2")
            {
                //类型为待办
                if (monthPlanView.ProcessType == "1")
                {
                    foreach (UIFunctionView item in menuActions)
                    {
                        string disabled = "";
                        if (item.ActionCode == "Withdraw" || item.ActionCode == "Receipt" || item.ActionCode == "Reminders")
                        {
                            disabled = "disabled='false'";
                        }
                        else if (item.ActionCode == "Back")
                        {
                            FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(monthPlanView.FlowCode, false, monthPlanView.AssociatedNodeCode);
                            if (flowNodeView.NodeType == 1)
                            {
                                disabled = "disabled='false'";
                            }
                        }
                        else if (item.ActionCode == "Cancel")
                        {
                            FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(monthPlanView.FlowCode, false, monthPlanView.AssociatedNodeCode);
                            if (flowNodeView.NodeLevel > 1 || flowNodeView.NodeType == 1)
                            {
                                disabled = "disabled='false'";
                            }
                        }
                        sb.Append(ToolButton(item, disabled));
                    }
                }
                //类型为传阅
                else
                {
                    foreach (UIFunctionView item in menuActions)
                    {
                        string disabled = "disabled='false'";
                        if (item.ActionCode == "Circulated" || item.ActionCode == "Receipt")
                        {
                            disabled = "";
                        }
                        sb.Append(ToolButton(item, disabled));
                    }
                }
            }
            #endregion

            #region 已办列表
            else if (monthPlanView.SourceType == "3")
            {
                //流转已办
                if (monthPlanView.ProcessType == "1")
                {
                    foreach (UIFunctionView item in menuActions)
                    {
                        string disabled = "disabled='false'";
                        if (monthPlanView.HandleState != "2" && monthPlanView.HandleState != "3")
                        {
                            if (item.ActionCode == "Withdraw")
                            {
                                //获取撤回到的节点信息
                                FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(monthPlanView.FlowCode, false, monthPlanView.ProcessdOrCirculatedNodeCode);
                                List<FlowNodeView> lstCirculationNode = new List<FlowNodeView>();
                                Dictionary<string, List<FlowNodeView>> dicConditionAndCirculationNode = new Dictionary<string, List<FlowNodeView>>();
                                bool isCanWithdraw = CanWithdraw(flowNodeView, monthPlanView, lstCirculationNode, dicConditionAndCirculationNode);
                                if (isCanWithdraw)
                                {
                                    disabled = "";
                                }
                            }
                            else if (item.ActionCode == "Circulated" || item.ActionCode == "Reminders")
                            {
                                disabled = "";
                            }
                        }
                        sb.Append(ToolButton(item, disabled));
                    }
                }
                //回退已办、终止已办
                else if (monthPlanView.ProcessType == "2" || monthPlanView.ProcessType == "3" || monthPlanView.ProcessType == "6")
                {
                    SetAllDisabled(menuActions, sb);
                }
                //本人传阅或者已阅
                else
                {
                    SetOneButtonEnabled(menuActions, sb, "Circulated");
                }
            }
            #endregion

            //流程消息
            else if (monthPlanView.SourceType == "4")
            {
                SetAllDisabled(menuActions, sb);
            }

            ViewBag.ToolBarInfo = sb.ToString();
        }

        private void SetAllDisabled(List<UIFunctionView> menuActions, StringBuilder sb)
        {
            foreach (UIFunctionView item in menuActions)
            {
                sb.Append(ToolButton(item, "disabled='false'"));
            }
        }

        private void SetOneButtonEnabled(List<UIFunctionView> menuActions, StringBuilder sb, string code)
        {
            foreach (UIFunctionView item in menuActions)
            {
                string disabled = "disabled='false'";
                if (item.ActionCode == code)
                {
                    disabled = "";
                }
                sb.Append(ToolButton(item, disabled));
            }
        }

        public string ToolButton(UIFunctionView item, string disabled = "")
        {
            return "<a href='javascript:void(0)' id='btn" + item.ActionCode + "' class='easyui-linkbutton' onclick='" + item.MenuCode + "." + item.ActionCode + "()' data-options='plain:true,iconCls:\"" + item.Icon + "\"'" + disabled + ">" + item.ActionName + "</a>";
        }
        #endregion

        #region 判断是否有撤回权限
        /// <summary>
        /// 判断是否有撤回权限
        /// </summary>
        /// <param name="flowNodeView">撤回到的节点信息</param>
        /// <param name="recordID">单据ID</param>
        /// <param name="lstCirculationNode">根据withdrawNodeCode获取要流转的节点列表</param>
        /// <param name="dicConditionAndCirculationNode">根据withdrawNodeCode获取条件节点流转的节点字典</param>
        /// <returns></returns>
        private bool CanWithdraw(FlowNodeView flowNodeView, MonthPlanView monthPlanView, List<FlowNodeView> lstCirculationNode, Dictionary<string, List<FlowNodeView>> dicConditionAndCirculationNode)
        {
            //分析撤回到的节点的XML里面的circulationCell，获取节点Code数组
            string[] arrFlowNodeCode = GetNodeCodeByXMLForCirculation(flowNodeView.NodeXML, monthPlanView.ID.ToString());

            //根据第一次获取到的节点数组，获取所有的中间经过的条件节点和流转节点
            foreach (string flowNodeCode in arrFlowNodeCode)
            {
                List<FlowNodeView> lstConditionAndCirculationNode = new List<FlowNodeView>();
                GetConditionAndCirculationNode(monthPlanView.FlowCode, flowNodeCode, monthPlanView.ID.ToString(), monthPlanView.ProcessdOrCirculatedUserDepartment, lstCirculationNode, lstConditionAndCirculationNode);
                dicConditionAndCirculationNode.Add(flowNodeCode, lstConditionAndCirculationNode);
            }

            //判断是否流转的节点对应的每个人在待办里面都能找到
            List<BaklogTaskView> lstBaklogTask = BaklogTaskService.GetBaklogTaskByRecordID(monthPlanView.ID.ToString());
            foreach (FlowNodeView circulationNode in lstCirculationNode)
            {
                string[] processDepartmentAndPersonArr = circulationNode.DefaultProcessPerson.Split(',');
                foreach (string processDepartmentAndPerson in processDepartmentAndPersonArr)
                {
                    string[] subProcessDepartmentAndPersonArr = processDepartmentAndPerson.Split('|');

                    //是否找不到待办
                    BaklogTaskView existsBaklogTaskView = lstBaklogTask.SingleOrDefault(b => b.CurrentFlowNodeCode == circulationNode.NodeCode && b.CurrentProcessPerson == subProcessDepartmentAndPersonArr[1]);
                    if (existsBaklogTaskView == null)
                    {
                        return false;
                    }

                    //是否点击了保存按钮
                    if (monthPlanView.SaveState == "1")
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 根据节点的XML获取流转节点Code
        /// </summary>
        /// <param name="nodeXML">节点的XML</param>
        /// <param name="recordID">单据ID</param>
        /// <returns></returns>
        private string[] GetNodeCodeByXMLForCirculation(string nodeXML, string recordID)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(nodeXML);
            XmlNodeList nodeList = doc.SelectNodes("NodeXML/circulationCell");
            string getType = nodeList[0].SelectSingleNode("getType").InnerText;
            string processNodeCode = string.Empty;
            if (getType.ToLower() == "value")
            {
                processNodeCode = nodeList[0].SelectSingleNode("cellsName").InnerText;
            }
            else
            {
                string functionName = nodeList[0].SelectSingleNode("functionName").InnerText;
                Hashtable para = new Hashtable();
                para.Add("IsGetBusinessData", true);
                para.Add("RecordID", recordID);
                XmlNode paraNode = nodeList[0].SelectSingleNode("functionParam");
                if (paraNode != null)
                {
                    para.Add(paraNode.Name, paraNode.InnerText);
                }
                processNodeCode = FlowUtilsService.ExecuteCommand(functionName, para) as string;
            }
            return processNodeCode.Split(',');
        }

        /// <summary>
        /// 获取所有的中间经过的条件节点和流转节点
        /// </summary>
        /// <param name="flowCode">流程编码</param>
        /// <param name="flowNodeCode">流程节点编码</param>
        /// <param name="recordID">单据ID</param>
        /// <param name="dicCirculationNode">记录流转节点的字典</param>
        /// <param name="lstConditionAndCirculationNode">记录条件节点和流转节点的List</param>
        private void GetConditionAndCirculationNode(string flowCode, string flowNodeCode, string recordID, string processUserDepartment, List<FlowNodeView> lstCirculationNode, List<FlowNodeView> lstConditionAndCirculationNode)
        {
            FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(flowCode, false, flowNodeCode);
            lstConditionAndCirculationNode.Add(flowNodeView);
            if (flowNodeView.NodeType == 2)
            {
                //如果是条件节点，获取条件节点的XML数据并解析，递归调用
                string[] arrFlowNodeCode = GetNodeCodeByXMLForCirculation(flowNodeView.NodeXML, recordID);
                foreach (string nextNodeCode in arrFlowNodeCode)
                {
                    GetConditionAndCirculationNode(flowCode, nextNodeCode, recordID, processUserDepartment, lstCirculationNode, lstConditionAndCirculationNode);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(flowNodeView.NodeXML))
                {
                    flowNodeView.DefaultProcessPerson = GetDefaultProcessPerson(flowNodeView.NodeXML, processUserDepartment);
                }
                lstCirculationNode.Add(flowNodeView);
            }
        }

        /// <summary>
        /// 获取缺省处理人和部门
        /// </summary>
        /// <param name="docPerson">节点xml文档</param>
        /// <param name="recordID">单据ID</param>
        /// <returns></returns>
        private string GetDefaultProcessPerson(string nodeXML, string processUserDepartment)
        {
            string defaultProcessPerson = string.Empty;
            XmlDocument docPerson = new XmlDocument();
            docPerson.LoadXml(nodeXML);
            XmlNode personNode = docPerson.SelectSingleNode("NodeXML/defaultProcessPerson");
            if (personNode != null)
            {
                string processPersonGetType = personNode.SelectSingleNode("getType").InnerText;
                if (processPersonGetType == "value")
                {
                    defaultProcessPerson = personNode.SelectSingleNode("presonList").InnerText;
                }
                else
                {
                    string functionName = personNode.SelectSingleNode("functionName").InnerText;
                    Hashtable para = new Hashtable();
                    para.Add("OrgCode", processUserDepartment);
                    XmlNode paraNode = personNode.SelectSingleNode("functionParam");
                    if (paraNode != null)
                    {
                        para.Add(paraNode.Name, paraNode.InnerText);
                    }
                    defaultProcessPerson = FlowUtilsService.ExecuteCommand(functionName, para) as string;
                }
            }
            return defaultProcessPerson;
        }
        #endregion

        #region 保存
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Save(MonthPlanView model)
        {
            try
            {
                string message = string.Empty;
                if (ValidateYearAndMonth(model, ref message) && ValidateInputAmount(model, ref message))
                {
                    if (model.SourceType == "1")
                    {
                        MonthPlanView monthPlanView = MonthPlanService.GetMonthPlanByID(model.ID);
                        if (monthPlanView == null)
                        {
                            List<BaklogTaskView> addList = new List<BaklogTaskView>();
                            addList.Add(new BaklogTaskView()
                            {
                                ID = GuidHelper.NewGuid(),
                                RecordID = model.ID.ToString(),
                                TaskType = model.FlowCode,
                                RequestDate = model.RequestDate,
                                CurrentFlowNodeCode = model.AssociatedNodeCode,
                                CurrentProcessPersonDepartment = model.LastUpdateUserDepartment,
                                CurrentProcessPerson = model.LastUpdateUser,
                                NodeLevel = 1
                            });
                            BaklogTaskService.AddBaklogTask(addList);
                        }
                    }
                    model.LastUpdateTime = DateTime.Now;
                    model.SaveState = "1";

                    decimal totalCurrentMonthActualCompletedMoneyNum = 0;
                    decimal totalNextMonthPlanMoneyNum = 0;
                    List<MonthPlanDetailsView> saveList = new List<MonthPlanDetailsView>();
                    if (!string.IsNullOrEmpty(model.MonthPlanDetailListJson as string))
                    {
                        string monthPlanDetailListJsonNew = "{\"lstMonthPlanDetailView\":" + model.MonthPlanDetailListJson + "}";
                        XmlNode nodeList = XMLJsonUtils.JsonToXml(monthPlanDetailListJsonNew).SelectSingleNode("root/lstMonthPlanDetailView");
                        foreach (XmlNode childNode in nodeList.ChildNodes)
                        {
                            string currentMonthActualCompletedAmount = childNode.SelectSingleNode("CurrentMonthActualCompletedAmount").InnerText;
                            string nextMonthPlanAmount = childNode.SelectSingleNode("NextMonthPlanAmount").InnerText;
                            if (!string.IsNullOrEmpty(currentMonthActualCompletedAmount) || !string.IsNullOrEmpty(nextMonthPlanAmount))
                            {
                                Guid id = childNode.SelectSingleNode("ID").InnerText.ToGuid();
                                MonthPlanDetailsView monthPlanDetailsView = saveList.SingleOrDefault(t => t.ID == id);
                                string isBelongToMoneyNum = childNode.SelectSingleNode("IsBelongToMoneyNum").InnerText;
                                string unit = childNode.SelectSingleNode("Unit").InnerText;
                                if (monthPlanDetailsView == null)
                                {
                                    if (isBelongToMoneyNum == "0")
                                    {
                                        saveList.Add(new MonthPlanDetailsView()
                                        {
                                            ID = id,
                                            MonthPlanID = model.ID,
                                            StatisticsItemID = childNode.SelectSingleNode("StatisticsItemID").InnerText.ToGuid(),
                                            CurrentMonthActualCompletedEngineeringNum = currentMonthActualCompletedAmount,
                                            NextMonthPlanEngineeringNum = nextMonthPlanAmount
                                        });
                                    }
                                    else
                                    {
                                        saveList.Add(new MonthPlanDetailsView()
                                        {
                                            ID = id,
                                            MonthPlanID = model.ID,
                                            StatisticsItemID = childNode.SelectSingleNode("StatisticsItemID").InnerText.ToGuid(),
                                            CurrentMonthActualCompletedMoneyNum = currentMonthActualCompletedAmount,
                                            NextMonthPlanMoneyNum = nextMonthPlanAmount
                                        });
                                        TotalMoney(unit, currentMonthActualCompletedAmount, ref totalCurrentMonthActualCompletedMoneyNum);
                                        TotalMoney(unit, nextMonthPlanAmount, ref totalNextMonthPlanMoneyNum);
                                    }
                                }
                                else
                                {
                                    if (isBelongToMoneyNum == "0")
                                    {
                                        monthPlanDetailsView.CurrentMonthActualCompletedEngineeringNum = currentMonthActualCompletedAmount;
                                        monthPlanDetailsView.NextMonthPlanEngineeringNum = nextMonthPlanAmount;
                                    }
                                    else
                                    {
                                        monthPlanDetailsView.CurrentMonthActualCompletedMoneyNum = currentMonthActualCompletedAmount;
                                        monthPlanDetailsView.NextMonthPlanMoneyNum = nextMonthPlanAmount;
                                        TotalMoney(unit, currentMonthActualCompletedAmount, ref totalCurrentMonthActualCompletedMoneyNum);
                                        TotalMoney(unit, nextMonthPlanAmount, ref totalNextMonthPlanMoneyNum);
                                    }
                                }
                            }
                        }
                    }
                    model.TotalCurrentMonthActualCompletedMoneyNum = totalCurrentMonthActualCompletedMoneyNum.ToString();
                    model.TotalNextMonthPlanMoneyNum = totalNextMonthPlanMoneyNum.ToString();
                    MonthPlanService.SaveMonthPlan(model, saveList);
                    return Content("保存成功！");
                }
                else
                {
                    return Content(message);
                }

            }
            catch (Exception ex)
            {
                return Content("保存失败：" + ex.Message);
            }
        }

        private bool ValidateYearAndMonth(MonthPlanView model, ref string message)
        {
            MonthPlanView monthPlanView = MonthPlanService.GetMonthPlanByID(model.ID);
            IQueryable<MonthPlan> lstMonthPlan = MonthPlanService.MonthPlans.Where(y => y.ProjectID == model.ProjectID && y.ContractType == model.ContractType && y.ContractID == model.ContractID && y.Year == model.Year && y.Month == model.Month);
            if (monthPlanView == null)
            {
                if (lstMonthPlan.Count() > 0)
                {
                    message = "统计周期【" + model.Year + "年" + model.Month + "月】已经存在！";
                    return false;
                }
            }
            else
            {
                if (lstMonthPlan.Count() > 1)
                {
                    message = "统计周期【" + model.Year + "年" + model.Month + "月】已经存在！";
                    return false;
                }
            }
            return true;
        }

        private bool ValidateInputAmount(MonthPlanView model, ref string message)
        {
            bool isPass = true;
            if (!string.IsNullOrEmpty(model.MonthPlanDetailListJson as string))
            {
                string monthPlanDetailListJsonNew = "{\"lstMonthPlanDetailView\":" + model.MonthPlanDetailListJson + "}";
                XmlNode nodeList = XMLJsonUtils.JsonToXml(monthPlanDetailListJsonNew).SelectSingleNode("root/lstMonthPlanDetailView");
                foreach (XmlNode childNode in nodeList.ChildNodes)
                {
                    string statisticsItemName = childNode.SelectSingleNode("StatisticsItemName").InnerText;
                    if (!ValidateInputSingleAmount(statisticsItemName, childNode.SelectSingleNode("CurrentMonthActualCompletedAmount").InnerText, childNode.SelectSingleNode("Unit").InnerText, ref message))
                    {
                        continue;
                    }
                    if (!ValidateInputSingleAmount(statisticsItemName, childNode.SelectSingleNode("NextMonthPlanAmount").InnerText, childNode.SelectSingleNode("Unit").InnerText, ref message))
                    {
                        continue;
                    }
                }
            }
            if (!string.IsNullOrEmpty(message))
            {
                isPass = false;
                message = message.Trim(',') + "的金额格式不符合单位里面的定义！";
            }
            return isPass;
        }

        private bool ValidateInputSingleAmount(string statisticsItemName, string amount, string unit, ref string message)
        {
            if (!string.IsNullOrEmpty(amount))
            {
                if (unit.Contains('/'))
                {
                    string[] amountArr = amount.Split('/');
                    if (amountArr.Length == 1 || amountArr.Length == 2)
                    {
                        try
                        {
                            decimal value = Convert.ToDecimal(amountArr[0]);
                        }
                        catch (Exception ex)
                        {
                            message += "【" + statisticsItemName + "】,";
                            return false;
                        }

                        if (amountArr.Length == 2)
                        {
                            try
                            {
                                decimal value = Convert.ToDecimal(amountArr[1]);
                            }
                            catch (Exception ex)
                            {
                                message += "【" + statisticsItemName + "】,";
                                return false;
                            }
                        }
                    }
                    else
                    {
                        message += "【" + statisticsItemName + "】,";
                        return false;
                    }
                }
                else
                {
                    try
                    {
                        decimal value = Convert.ToDecimal(amount);
                    }
                    catch (Exception ex)
                    {
                        message += "【" + statisticsItemName + "】,";
                        return false;
                    }
                }
            }
            return true;
        }

        private void TotalMoney(string unit, string moneyStr, ref decimal total)
        {
            if (!string.IsNullOrEmpty(moneyStr))
            {
                if (unit == "万元")
                {
                    total += Convert.ToDecimal(moneyStr);
                }
                else
                {
                    total += Convert.ToDecimal(moneyStr) / 10000;
                }
            }
        }
        #endregion

        public ActionResult Withdraw(MonthPlanView model, string withdrawNodeCode)
        {
            try
            {
                //获取撤回到的节点信息
                FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(model.FlowCode, false, withdrawNodeCode);
                List<FlowNodeView> lstCirculationNode = new List<FlowNodeView>();
                Dictionary<string, List<FlowNodeView>> dicConditionAndCirculationNode = new Dictionary<string, List<FlowNodeView>>();
                bool isCanWithdraw = CanWithdraw(flowNodeView, model, lstCirculationNode, dicConditionAndCirculationNode);
                if (isCanWithdraw)
                {
                    FlowUtilsService.Withdraw(flowNodeView, model.FlowCode, model.ID.ToString(), model.ProcessdOrCirculatedUserDepartment, model.RequestDate, lstCirculationNode, dicConditionAndCirculationNode);
                    return Content("Success");
                }
                else
                {
                    return Content("已经有人处理，不能撤回！");
                }
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        public ActionResult Cancel(string flowCode, string id)
        {
            try
            {
                FlowUtilsService.Cancel(flowCode, User.Identity.Name, id);
                MonthPlanView monthPlanView = MonthPlanService.GetMonthPlanByID(id.ToGuid());
                monthPlanView.HandleState = "3";
                MonthPlanService.SaveMonthPlan(monthPlanView, new List<MonthPlanDetailsView>(), false);
                return Content("Success");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        public ActionResult Reminders(string flowCode, string id)
        {
            try
            {
                FlowUtilsService.Reminders(id, flowCode, User.Identity.Name);
                return Content("Success");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        public ActionResult GenerateGraph(string flowCode, string id)
        {
            MonthPlanView monthPlanView = MonthPlanService.GetMonthPlanByID(id.ToGuid());
            string handleState = "";
            if (monthPlanView != null)
            {
                handleState = monthPlanView.HandleState;
            }
            WorkFlowView workFlowView = FlowUtilsService.GenerateGraph(flowCode, id, handleState);
            return Json(workFlowView, JsonRequestBehavior.AllowGet);
        }

        #region 统计分析
        public ActionResult StatisticalAnalysisList()
        {
            return View();
        }

        public ActionResult GetStatisticalAnalysisList(string projectID, string contractType, string year, string monthStr, string contractIDStr)
        {
            Guid guidProjectID = string.IsNullOrEmpty(projectID) ? GuidHelper.NewGuid() : projectID.ToGuid();
            List<Guid> lstContractID = new List<Guid>();
            string[] contractIDArr = contractIDStr.Split(',');
            foreach (string contractID in contractIDArr)
            {
                lstContractID.Add(contractID.ToGuid());
            }

            List<string> lstMonth = new List<string>();
            string[] monthArr = monthStr.Split(',');
            foreach (string month in monthArr)
            {
                lstMonth.Add(month);
            }
            return Json(MonthPlanService.GetStatisticalAnalysisList(guidProjectID, contractType, year, lstMonth, lstContractID), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetStatisticalAnalysisDetailList(string projectID, string contractType, string year, string monthStr, string contractID)
        {
            Guid guidProjectID = projectID.ToGuid();
            Guid guidContractID = contractID.ToGuid();
            List<string> lstMonth = new List<string>();
            string[] monthArr = monthStr.Split(',');
            foreach (string month in monthArr)
            {
                lstMonth.Add(month);
            }
            return Json(MonthPlanService.GetStatisticalAnalysisDetailList(guidProjectID, contractType, year, lstMonth, guidContractID), JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
